package dyyx.web;

import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import dyyx.drools.DroolsUtil;
import dyyx.drools.demo1.RuleContext;
import dyyx.util.CommUtil;
import dyyx.util.RunStatusUtil;

public class WebAction  {
	
	private static final String DATA = "data";
	private static final String ERROR = "error";
	
	private static final Random rand = new Random();


	
	public static void status(HttpServletRequest request, Map<String,Object> map) throws Exception {
		String type = request.getParameter("type");
		if(StringUtils.isBlank(type)){
			type = "status";
		}
		map.put("type", type);
		map.put("now", CommUtil.getNowDateString());
		map.put("path", request.getRealPath("/"));

		
		if("status".equals(type)){
			map.put(DATA, RunStatusUtil.runStatus);
			return;
		}	
		if("gc".equals(type)){
			System.gc();
			RunStatusUtil.runStatus.updateCount("gcInvoke");
			map.put(DATA, "gc invoke at "+CommUtil.getNowDateString());
			return;
		}	
		
		if("compile".equals(type)){
			long start = System.currentTimeMillis();
			DroolsUtil.compile();	
			long end = System.currentTimeMillis();
			long time = end - start;
			map.put("runTime", time);		
			map.put(DATA, "drools compile at "+CommUtil.getNowDateString());
			
			return;
		}	
		
        if("run".equals(type)){
        	
        	String name =  request.getParameter("name");
        	String agestr =  request.getParameter("age");
        	if(StringUtils.isBlank(name)){
        		name = "tiger";
        	}
        	
        	int age = CommUtil.getInt(agestr);
        	if(age<=0){
        		age = rand.nextInt(100);
        	}
        	RuleContext context = new RuleContext();
        	context.setName(name);
        	context.setAge(age);
			long start = System.currentTimeMillis();
			DroolsUtil.run(context);
			long end = System.currentTimeMillis();
			long time = end - start;

			map.put("result", context);
			map.put("runTime", time);


			map.put(DATA, "drools run at "+CommUtil.getNowDateString());
			
			return;
		}	
		
		
		
	}
	

}